import {defineStore} from "pinia";
import {reqLogin, reqUserInfo, reqLogout} from "@/api/user";
import {ref} from "vue";
import {UserState} from "@/stores/modules/types/type.ts";
import {SET_TOKEN, GET_TOKEN, REMOVE_TOKEN} from "@/utils/token.ts";
import {constantRoutes} from "@/router/routes.ts";
import type {loginForm, loginRes, userInfo} from "@/api/user/type.ts";
// 用户仓库

const useUserStore = defineStore('User',():UserState=>{
    // 登录页获取服务器返回的token值，用于之后携带token访问服务器
    const token = ref(GET_TOKEN())
    const menuRoutes = ref(constantRoutes);
    const username = ref('')
    const avatar = ref('')
    const userLogin = async (data:loginForm) => {
        const result:loginRes = await reqLogin(data)
        console.log("src/stores/modules/user.ts:", result)
    //     登录成功， code=200， 则获取到token
        if(result.code === 200) {
            token.value = (result.data as string)
            // 本地存储持久化
            SET_TOKEN(result.data as string)

            return 'ok'
        } else {
        //     失败逻辑
            return Promise.reject(new Error(result.message as string))
        }
    }

    // 获取用户信息
    const userInfo = async () => {
        const result:userInfo = await reqUserInfo()
        if(result.code === 200) {
            username.value = result.data.name
            avatar.value = result.data.avatar
            return 'ok'
        }else {
            return Promise.reject(new Error(result.message))
        }
    }

    const userLogOut = async () => {
        const result:any = await reqLogout()
        if(result.code === 200) {
            token.value = ''
            avatar.value = ''
            username.value = ''
            REMOVE_TOKEN()
            return 'ok'
        }else {
            return Promise.reject(new Error(result.message))
        }
    }

    return {
        token,
        menuRoutes,
        username,
        avatar,
        userLogin,
        userInfo,
        userLogOut
    }
})

export default useUserStore;